package com.zxd.interview.jmm;

/**
 * synchronized 实现happens-before规则的案例
 */
public class HappensBefore {


    int a = 1;

    // 修复问题只需要给b变量加上 volatile

    //    int b = 2;
    int b = 2;

    int c = 5;
    int d = 7;

    private void change(){
        a = 3;
        b = 6;
        c = 1;
        // happends-before原则前面的操作都可以看到
//        synchronized (this){
            d = 8;
//        }
    }

    private void print(){
        int aa;
        // 这里对于第一个变量加锁，保证在打印之前其他线程操作都可以看到
//        synchronized (this) {
            aa = a;
//        }
        int bb = b;
        int cc = c;
        int dd = d;
        System.out.println();
        System.out.print("aa => "+ aa + ", "+" bb => "+ bb + ", "+" cc => "+ cc + ", "+ " dd => "+ dd);
        System.out.println();
    }

    public static void main(String[] args) {
        while(true){
            HappensBefore visibility = new HappensBefore();
            new Thread(()->{
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                visibility.change();
            }).start();

            new Thread(()->{
                try {
                    Thread.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                visibility.print();
            }).start();
        }
    }

}
